package controller;

import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

import multiformat.Calculator;
import multiformat.FormatException;
import multiformat.NumberBaseException;

public class OperandController extends JPanel implements ActionListener {

	private static final long serialVersionUID = 1L;
	
	private Calculator model;
		
	private JButton btnAddOperand;
	private JButton btnDelOperand;
	
	public OperandController(Calculator model) {
		this.model = model;
		
		this.setLayout(new GridLayout(1,2));
		

		//initialize buttons
		this.btnAddOperand = new JButton("Set");
		this.btnAddOperand.setBackground(Color.LIGHT_GRAY);
		
		this.btnDelOperand = new JButton("Del");
		this.btnDelOperand.setBackground(Color.LIGHT_GRAY);
		
		this.add(btnAddOperand);
		this.add(btnDelOperand);
		
		//add actionlisteners to buttons
		this.btnAddOperand.addActionListener(this);
		this.btnDelOperand.addActionListener(this);
		
		this.validate();
		
		this.setVisible(true);
		
	}

	
	
	@Override
	public void actionPerformed(ActionEvent e) {
		
		Object source = e.getSource();

		if(source == btnAddOperand){
			String newval = JOptionPane.showInputDialog("Please provide a new Operand", "0.0");
			
			if(newval != null) {
				try {
					model.addOperand(newval);
				} catch (FormatException | NumberBaseException e1) {
					JOptionPane.showMessageDialog(this,e1.getMessage(),"An error has ocurred: ", JOptionPane.ERROR_MESSAGE);
				}
			}
		}else if(source == btnDelOperand) {
			int confirm = JOptionPane.showConfirmDialog(null, "Are you sure?");
			if(confirm == 0 ) {
				model.delete();
			}
		}
	}
}
